<style lang="less">
  @import '../../../styles/common.less';
  @import '../draggable-list/draggable-list.less';
</style>
<template>
  <div >
    <!--页面列表模块-->
    <Row :gutter="10" class="margin-top-10">
      <PageTemplate></PageTemplate>
    </Row>

    <!--页面设计模块-->
    <Row :gutter="10" class="margin-top-10">
      <!--设计器元素-->
      <Col span="6">
      <Alert banner type="warning">
        <Icon type="compose" />
        <Poptip  trigger="hover" placement="top-start" content="请拖动设计器下的组件到右边的幕布完成表单的设计">
          页面设计器
        </Poptip>
      </Alert>

      <card>
        <Form >
          <draggable :clone="cloneData" :list="layout_list" :options="dragOptions1">
            <transition-group class="form-list-group" type="transition" :name="'flip-list'" tag="div">
              <renders v-for="(element,index) in layout_list" :key="index" :ele="element.ele" :obj="element.obj || {}">
              </renders>
            </transition-group>
          </draggable>
        </Form>
        <Modal v-model="showModal" :title="'配置' + modalFormData.modalTitle + '属性'" :mask-closable="false">
          <Form class="form_content" :label-width="100" :model="modalFormData" ref="modalFormData">
            <FormItem label="控件名称：" v-if="typeof modalFormData.label != 'undefined'" >
              <i-input v-model="modalFormData.label"  placeholder="请输入控件名称" :maxlength="6" ></i-input>
            </FormItem>
            <FormItem label="name属性：" v-if="typeof modalFormData.name != 'undefined'">
              <i-input v-model="modalFormData.name" placeholder="" ></i-input>
            </FormItem>
            <!--栅格配置-->
            <FormItem label="列配置项：" v-if="typeof modalFormData.grids != 'undefined'">
              <Form-item v-for="(item,index) in modalFormData.grids"
                         :label="'栅格' + (index+1)">
                <Row>
                  <i-col span="4">
                    <i-input v-model="item.span" placeholder="输入栅格值"   @change.native="handleGridChange"></i-input>
                  </i-col>
                  <i-col span="4" offset="1">
                    <i-button type="error" @click="handleGridRemove(item,index)">删除</i-button>
                  </i-col>
                </Row>
              </Form-item>
              <Form-item>
                <Row>
                  <i-col offset="3" span="12">
                    <i-button type="success" long @click="handleGridAdd" icon="plus-round">新增</i-button>
                  </i-col>
                </Row>
              </Form-item>
            </FormItem>
            <FormItem label="栅格间距：" v-if="modalFormData.type == 'grid'">
              <InputNumber :formatter="value => `${value}px`" :parser="value => value.replace('px', '')" v-model="modalFormData.props.gutter" placeholder="请输入栅格间距">
              </InputNumber>
            </FormItem>
            <FormItem label="水平排列方式：" v-if="modalFormData.type == 'grid'">
              <Select v-model="modalFormData.props.justify" class="inline-block" style="width: 150px" @on-change="handleJustifyChange">
                <Option v-for="(item,index) in modalFormData.justifyOptions" :key="index" :value="item.value">{{item.label}}</Option>
              </Select>
            </FormItem>
            <FormItem label="垂直排列方式：" v-if="modalFormData.type == 'grid'">
              <Select v-model="modalFormData.props.align" class="inline-block" style="width: 150px" @on-change="handleAlignChange">
                <Option v-for="(item,index) in modalFormData.alignOptions" :key="index" :value="item.value">{{item.label}}</Option>
              </Select>
            </FormItem>
            <!--分割线配置-->
            <FormItem label="标题位置：" v-if="modalFormData.type == 'divider'">
              <Select v-model="modalFormData.props.orientation" class="inline-block" style="width: 150px" @on-change="handleAlignChange">
                <Option v-for="(item,index) in modalFormData.orientationOptions" :key="index" :value="item.value">{{item.label}}</Option>
              </Select>
            </FormItem>
            <FormItem label="关联数据：" v-if="typeof modalFormData.relation != 'undefined'">
              <!-- 当绑定name并且当前relationList存在数据时候才可以关联字段 -->
              <Checkbox :disabled="!modalFormData.name || !relationList.length" v-model="modalFormData.relation">是否关联字段</Checkbox>
            </FormItem>
            <FormItem label="关联配置：" v-if="typeof modalFormData.relation != 'undefined' && modalFormData.relation">
              <Select v-model="modalFormData.relation_name" class="inline-block" style="width: 150px" @on-change="_=>modalFormData.relation_value = ''">
                <Option :disabled="item.obj.name == modalFormData.name" v-for="(item,index) in relationList" :key="index" :value="item.obj.name">{{item.obj.label}}</Option>
              </Select>
              <p class="inline-block padder-sm">等于</p>
              <Select v-model="modalFormData.relation_value" class="inline-block" style="width: 150px">
                <Option v-for="(item,index) in relationValue" :key="index" :value="item.label_value">{{item.label_name}}</Option>
              </Select>
            </FormItem>
            <FormItem label="placeholder：" v-if="typeof modalFormData.placeholder != 'undefined'">
              <i-input v-model="modalFormData.placeholder" placeholder="请输入placeholder"></i-input>
            </FormItem>
            <FormItem label="最大长度：" v-if="typeof modalFormData.maxLength != 'undefined'">
              <InputNumber v-model="modalFormData.maxLength" placeholder="请输入文本限制最大长度">
              </InputNumber>
            </FormItem>
            <FormItem label="最大限制：" v-if="typeof modalFormData.maxSize != 'undefined'">
              <InputNumber :formatter="value => `${value}kb`" :parser="value => value.replace('kb', '')" v-model="modalFormData.maxSize" placeholder="请输入上传文件最大限制">
              </InputNumber>
            </FormItem>
            <FormItem label="上边距：" v-if="typeof modalFormData.marginTop != 'undefined'">
              <InputNumber :formatter="value => `${value}px`" :parser="value => value.replace('px', '')" v-model="modalFormData.marginTop" placeholder="请输入标签上边距">
              </InputNumber>
            </FormItem>
            <FormItem label="左边距：" v-if="typeof modalFormData.marginLeft != 'undefined'">
              <InputNumber :formatter="value => `${value}px`" :parser="value => value.replace('px', '')" v-model="modalFormData.marginLeft" placeholder="请输入标签左边距">
              </InputNumber>
            </FormItem>
            <FormItem label="下边距：" v-if="typeof modalFormData.marginBottom != 'undefined'">
              <InputNumber :formatter="value => `${value}px`" :parser="value => value.replace('px', '')" v-model="modalFormData.marginBottom" placeholder="请输入标签下边距">
              </InputNumber>
            </FormItem>
            <FormItem label="校验错误：" v-if="typeof modalFormData.ruleError != 'undefined'">
              <i-input v-model="modalFormData.ruleError" placeholder="请输入校验错误提示"></i-input>
            </FormItem>
            <FormItem label="是否多选：" v-if="typeof modalFormData.multiple != 'undefined' && modalFormData.type != 'address'">
              <Checkbox v-model="modalFormData.multiple">多选</Checkbox>
            </FormItem>
            <FormItem label="仅支持图片：" v-if="typeof modalFormData.image != 'undefined'">
              <Checkbox v-model="modalFormData.image">是</Checkbox>
            </FormItem>
            <FormItem label="时间格式：" v-if="typeof modalFormData.format != 'undefined'">
              <RadioGroup v-model="modalFormData.format">
                <Radio label="yyyy年MM月dd日"></Radio>
                <Radio label="yyyy-MM-dd HH:mm"></Radio>
              </RadioGroup>
            </FormItem>
            <FormItem label="行内元素：" v-if="typeof modalFormData.inlineBlock != 'undefined'">
              <Checkbox v-model="modalFormData.inlineBlock">是</Checkbox>
            </FormItem>
            <FormItem label="显示行数：" v-if="typeof modalFormData.maxRows != 'undefined'">
              <Slider v-model="modalFormData.maxRows" :min="2" :max="10"></Slider>
            </FormItem>
            <FormItem label="标题大小：" v-if="typeof modalFormData.level != 'undefined'">
              <InputNumber :max="6" :min="1" v-model="modalFormData.level"></InputNumber>
            </FormItem>
            <FormItem label="字体颜色：" v-if="typeof modalFormData.color != 'undefined'">
              <ColorPicker v-model="modalFormData.color" />
            </FormItem>
          </Form>
          <div slot="footer">
            <Button type="text" @click="handleCancel">取消</Button>
            <Button type="primary" :loading="modalFormData.loading" @click="handleOk">确定</Button>
          </div>
        </Modal>
        <!-- <draggable class="wrapper"
                    @start="start"
                    @end="end">
           <i-button>Grid栅格布局</i-button>
         </draggable>-->
        <!--<Tabs value="layout">
          <TabPane label="布局元素" icon="ios-list-box-outline" name="layout">


          </TabPane>
          <TabPane label="表单元素" icon="ios-list-box-outline" name="form">
            <Row>
              <Input v-model="formNameQuery" placeholder="请输入表单名称..." style="width: 200px"/>
              <Button @click="handleRead" type="primary" icon="search">搜索</Button>
            </Row>
            <Row class="margin-top-10 searchable-table-con1">
              <DragableTable :sort=false refs="formTemplates" :columns-list="columns" v-model="records" @on-start="handleOnstart" @on-end="handleOnend"  ></DragableTable>
            </Row>
            <Row class="margin-top-10 searchable-table-con1">
              <Page :total="totalCount" :page-size="size" show-total @on-change="changePage"></Page>
            </Row>
          </TabPane>
          <TabPane label="表格元素" icon="ios-grid" name="table">
            <Row>
              <Input v-model="name" placeholder="请输入表格名称..." style="width: 200px"/>
              <Button @click="handleTableRead" type="primary" icon="search">搜索</Button>
            </Row>
            <Row class="margin-top-10 searchable-table-con1">
              <DragableTable :sort=false refs="tables" :columns-list="tableColumns" v-model="tableRecords" @on-start="handleTableOnstart" @on-end="handleTableOnend"  ></DragableTable>
            </Row>
            <Row class="margin-top-10 searchable-table-con1">
              <Page :total="tableTotalCount" :page-size="size" show-total @on-change="tableChangePage"></Page>
            </Row>
          </TabPane>
        </Tabs>-->
      </card>
      </col>

      <!--幕布-->
      <Col span="18">
      <Card >
        <Row :gutter="40">
          <Col span="12"><Alert style="margin: 15px 15px 15px;" type="warning" show-icon>(请拖动设计器下的组件到右边的幕布完成页面的设计)</Alert></Col>
          <Col span="12">
          <Button @click="handleSave" type="success" icon="ios-power" style="margin-top: 15px">保存页面</Button>
          </Col>
        </Row>
        <draggable :list="layout_item" :options="dragOptions1">
          <transition-group class="form-list-group" type="transition" :name="'flip-list'" tag="div" >
            <layoutRenders
                    v-for="(element,index) in layout_item" :key="index" :index="index" :ele="element.ele" @handleConfEle="confEle" @handleRemoveEle="removeEle"
                    :obj="element.obj || {}" :data="formData" @handleChangeVal="val => handleChangeVal(val,element)"
                    :sortableItem="layout_item" :config-icon="true">
            </layoutRenders>
          </transition-group>
        </draggable>
        <!-- <div class="dragging-tip-con">
           <transition name="dragging-tip">
             <span v-show="templateList.hasDragged">
               <Tabs type="card" closable @on-tab-remove="handleTabRemove" @on-click="handleTabsClick">
               <TabPane   v-for="(item, tabIndex) in templateList.panelList" :key="tabIndex+item.formName"   :label="item.formName">
                   <card>
                     <Form style="visibility:visible;" label-position="right" :label-width="100">
                       <renders  v-for="(element,index) in item.formTemplate" :key="index" :index="index" :ele="element.ele" :obj="element.obj || {}" :data="formData" @handleChangeVal="val => handleChangeVal(val,element)" :sortableItem="sortable_item" :config-icon="false">
                       </renders>
                     </Form>
                   </card>
                 <Row class="margin-top-10"></Row>
                 &lt;!&ndash;表格&ndash;&gt;
                   <p v-for="(item,index) in tableCard.tableList" v-if="item.tab==tabIndex" >
                   <card v-for="(element,index) in item.tables" :key="index">
                       <Icon type="ios-toggle"></Icon>{{element.name}}
                       <Button @click="handleRemove(index)" type="error" >移除</Button>
                     <TableRenders :obj="element"></TableRenders>
                   </card>
                   </p>
               </TabPane>
           </Tabs>

             </span>
           </transition>
         </div>-->

      </Card>
      </Col>
    </Row>
  </div>

</template>
<script>
import DragableTable from '../../tables/components/dragableTable';
import layout_list from "./custom_form/LayoutList";
import TableRenders from "./custom_form/components/Tables/TableRender"
import layoutRenders from "./custom_form/LayoutRender"
import draggable from "vuedraggable"
import api from "../../../libs/api"
import PageTemplate from "./page-template.vue"
import {Message}from 'iview'
import {eventBus} from "../../../libs/eventBus"
export default {
    components: {
        draggable,
        DragableTable,
        TableRenders,
        PageTemplate,
        layoutRenders
    },
    computed: {
        // 源拖拽配置
        dragOptions1() {
            return {
                animation: 0,
                ghostClass: "ghost",
                // 分组
                group: {
                    name: "shared",
                    pull: "clone",
                    revertClone: false
                },
                // 禁止拖动排序
                sort: false
            };
        },
        // 拖拽目的配置
        dragOptions2() {
            return {
                animation: 0,
                ghostClass: "ghost",
                group: {
                    // 只允许放置shared的控件,禁止pull
                    put: ["shared"]
                }
            };
        },
    },
    data() {
        return {
            layout_list: layout_list,
            layout_item:[],  //布局元素
            //表单列表
            records:[],  //表单列表
            totalCount:0,//表单列表总页数
            current: 1,//当前页
            size: 10,//页面大小
            totalPage: 0, //总条数
            formNameQuery:"",//表单名称
            templateList: {
                hasDragged: false,
                isDragging: false,
                oldIndex: 0,
                newIndex: 0,
                panelList: []
            },
            GridList: {

            },
            tableCard:{
                hasDragged: false,
                isDragging: false,
                oldIndex: 0,
                newIndex: 0,
                tableList: []
            },
            columns: [
                {
                    title: '表单名称',
                    key: 'formName'
                },
                {
                    title: '表单创建人',
                    key: 'createUserView'
                }
            ],
            sortable_item: [],
            showModal: false,
            // 深拷贝对象，防止默认空对象被更改
            // 颜色选择器bug，对象下color不更新
            modalFormData: {
                color: '',
                loading: false,
                props:{

                }
            },
            formData: {},
            pageName:"",  //页面名称
            pageTemplateId:"",  //页面模板Id
            //表格
            tableColumns:[
                {
                    title: '表格名称',
                    key: 'name'
                }
            ],
            tableRecords:[], //表格数据
            tableCurrent: 1,//表格前页
            tableTotalPage: 0, //表格总页数
            name:"", //表格名称查询
            tableTotalCount:0,//表格数据总页数
            currentActiveTab:0 //当前活动的tab
        };
    },
    methods: {
        cloneData(original) {
            // 添加一个modal标题
            original.obj.modalTitle = original.obj.label || "";
            // 深拷贝对象，防止默认空对象被更改
            return JSON.parse(JSON.stringify(original));
        },
        //start ,end ,add,update, sort, remove 得到的都差不多
        start: function (evt) {
            console.log("start....");
            console.log(evt)
        },
        end: function (evt) {

            console.log(evt)
            evt.item //可以知道拖动的本身
            evt.to    // 可以知道拖动的目标列表
            evt.from  // 可以知道之前的列表
            evt.oldIndex  // 可以知道拖动前的位置
            evt.newIndex  // 可以知道拖动后的位置
        },

        //移除tabs
        handleTabRemove (index) {
            let self=this;
            self.templateList.panelList.splice(index,1);
//                self.currentActiveTab=index-1<0?0:index-1;

        },
        //tabs点击事件
        handleTabsClick(index){
            this.currentActiveTab=index;
        },
        handleOnstart (from) {
            this.templateList.oldIndex = from;
            this.templateList.hasDragged = true;
            this.templateList.isDragging = true;
        },
        handleOnend (e) {
            console.log(e);
            this.templateList.newIndex = e.to;
            this.templateList.isDragging = false;
            let record=this.records[e.from];
            let template=JSON.parse( record.formTemplate || '[]');
            let colone=Object.assign({},record);
            colone.formTemplate=template;
            this.templateList.panelList.push(colone);
        },
        handleTableOnstart (from) {
            this.tableCard.oldIndex = from;
            this.tableCard.hasDragged = true;
            this.tableCard.isDragging = true;
        },
        handleTableOnend (e) {
            this.tableCard.newIndex = e.to;
            this.tableCard.isDragging = false;
            let record=this.tableRecords[e.from];
            let colone=Object.assign({},record);
            let tableList=this.tableCard.tableList.filter(v=>{
                    return v.tab==this.currentActiveTab;
                })||[];
            if(tableList.length!=0){
                tableList[0].tables.push(colone);
            }else{
                this.tableCard.tableList.push({"tab":this.currentActiveTab,"tables":[colone]});
            }
        },
        //移除表格
        handleRemove(index){
            let tableList=this.tableCard.tableList.filter(v=>{
                    return v.tab==this.currentActiveTab;
                })||[];
            tableList[0].tables.splice(index,1);
        },
        //读取列表数据
        handleRead(){
            let data = {};
            data.current = this.current;
            data.size = this.size;
            data.formNameQuery=this.formNameQuery;
            this.$get(api.formTemplates.base, data).then(response => {
                this.totalPage = this.util.calTotalPage(response.obj.total, this.size);
                this.totalCount = response.obj.total;
                this.records = [];
                for (let i in response.obj.records) {
                    this.records.push(response.obj.records[i])
                }
            });
        },
        //读取列表数据
        handleTableRead(){
            let data = {};
            data.current = this.tableCurrent;
            data.size = this.size;
            data.name=this.name;
            this.$get(api.dictionarys.table, data).then(response => {
                this.tableTotalPage = this.util.calTotalPage(response.obj.total, this.size);
                this.tableTotalCount = response.obj.total;
                this.tableRecords = [];
                for (let i in response.obj.records) {
                    this.tableRecords.push(response.obj.records[i])
                }
            });
        },
        //保存页面
        handleSave(){
            let self=this;
            if(this.templateList.panelList.length==0){
                Message.warning({content:"请先完成页面设计",duration:3});
                return false;
            }
            let pageTemplates=[];
            for(var index=0;index<this.templateList.panelList.length;index++){
                let template={};
                template.index=index;
                template.formTemplateId= this.templateList.panelList[index].id;
                let tableList=this.tableCard.tableList.filter(v=>{return v.tab==index})||[];
                template.tables= tableList.length>0?tableList[0].tables:[];
                pageTemplates.push(template);
            }
            this.$Modal.confirm({
                loading:true,
                render: (h) => {
                    return h('Input', {
                        props: {
                            value: self.pageName,
                            autofocus: true,
                            placeholder: '请输入页面名称'
                        },
                        on: {
                            input: (val) => {
                                self.pageName = val;
                            }
                        }
                    })
                },
                onOk: function() {
                    let modal = this;
                    modal.$data.buttonLoading = false;
                    //验证表单
                    if(self.pageName==""){
                        self.$Message.error('页面名称不允许为空',3);
                        return false;
                    }
                    //保存表单数据
                    let data={};
                    data.pageTemplate=JSON.stringify(pageTemplates);
                    data.pageName=self.pageName;
                    if(""==self.pageTemplateId){  //保存页面模板
                        self.$post(api.pageTemplates.base,data).then(response=>{
                            if(200==response.code){
                                self.handleReset();
                                modal.remove();
                            }
                        });
                    }else{
                        self.$put(api.pageTemplates.base+"/"+self.pageTemplateId,data).then(response=>{
                            if(200==response.code){
                                self.handleReset();
                                modal.remove();
                            }
                        });
                    }

                }
            });
        },
        //翻页
        changePage(index){
            this.current = index;
            this.handleRead();
        },
        //表格列表翻页
        tableChangePage(index){
            this.tableCurrent = index;
            this.handleTableRead();
        },
        // 清空
        handleReset() {
            this.pageName="";
            this.pageTemplateId="";
            this.templateList.panelList=[];
            this.tableCard.tableList=[];
            eventBus.$emit("freshPageList");
        },
        // 控件回填数据
        handleChangeVal(val, element) {
            this.$set(this.formData, element.obj.name, val);
        },
        // modal点击取消执行事件，清空当前modal内容
        handleCancel() {
            this.showModal = false;
            setTimeout(_ => {
                this.modalFormData = {
                    color: '',
                    loading: false,
                    props:{

                    }
                };
            }, 500)
        },
        // 显示modal,配置被克隆控件
        confEle(index) {
            const list_temp = Object.assign({}, this.layout_item[index]);
            for (let i in list_temp.obj) {
                this.modalFormData[i] = list_temp.obj[i];
            }
            // 配置项中未找到color，删除modalFormData中自带color属性
            if (!list_temp.obj['color']) delete this.modalFormData.color;
            // 设置被配置控件的index，便于完成配置找到相应对象赋值
            this.modalFormData.listIndex = index;
            // Vue 不能检测到对象属性的添加或删除
            this.modalFormData = Object.assign({}, this.modalFormData);
            this.showModal = true;

        },
        // 删除克隆控件
        removeEle(index) {
            let name = this.layout_item[index].obj.name;
            console.log(name);
            this.layout_item.splice(index, 1);
            if (!name) return;
            for (let i in this.layout_item) {
                // 当relation为true并且关联字段被确认
                if (this.layout_item[i].obj.relation && this.layout_item[i].obj.relation_name === name) {
                    this.$set(this.layout_item[i].obj, "relation", false);
                    this.$set(this.layout_item[i].obj, "relation_name", "");
                    this.$set(this.layout_item[i].obj, "relation_value", "");
                    break;
                }
            }
        },
        //确认配置
        handleOk(){

        },
        //删除栅格列配置
        handleGridRemove(item,index){
            this.modalFormData.grids.splice(index,1);
        },
        //添加栅格
        handleGridAdd(){
            this.modalFormData.grids.push({"span":0});
        },
        //栅格变化
        handleGridChange(value){
            let totalSpace=0;
            this.modalFormData.grids.forEach(item=>{
                totalSpace+=parseInt(item.span)
            })
        },
        //栅格水平方式布局变更
        handleJustifyChange(value){
            console.log(this.modalFormData);
            this.modalFormData.props.justify=value;
        },
        //栅格垂直方式布局变更
        handleAlignChange(value){
            this.modalFormData.props.align=value;
        }
    },
    watch: {
        showModal(val) {
            if (!val) {
                this.handleCancel();
            }
        }
    },
    mounted(){
        let self=this;
        //为了防止火狐浏览器拖拽的时候以新标签打开，此代码真实有效
        document.body.ondrop = function (event) {
            event.preventDefault();
            event.stopPropagation();
        }
        //回显页面
        eventBus.$on("showPageTemplate",function (page) {
            self.pageTemplateId=page.id;
            self.templateList.panelList=[];
            self.currentActiveTab=0;
            self.pageName=page.pageName;
            self.tableCard.tableList=[];
            let pageTemplate=JSON.parse(page.pageTemplate);
            pageTemplate.forEach(function (tab) {
                self.templateList.panelList.push(tab.formTemplate);
                self.tableCard.tableList.push({"tab":tab.index,"tables":tab.tables});
            });
        });
    },
    created() {
        let self=this;
        //读取列表数据
        self.handleRead();
        self.handleTableRead();
    }
};
</script>
<style>
  .form-list-group {
    min-height: 200px;
    /*padding: 20px !important;*/
  }
</style>